package ray.wx.util;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLUtil {
	private Document m_document;
	
	private NodeList m_list;
	
	public void init(InputStream is){		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			m_document = db.parse(is);
						
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int locateParent(String tagName){
		m_list = m_document.getElementsByTagName(tagName);
        return m_list.getLength();
	}
	
	public String getValueByName(String tagName){
     	Element element = (Element) m_list.item(0);
		return element.getElementsByTagName(tagName).item(0).getFirstChild().getNodeValue();
	}
	
	public String getValueByName(String tagName, int num){
     	Element element = (Element) m_list.item(num);
		return element.getElementsByTagName(tagName).item(0).getFirstChild().getNodeValue();
	}
	
	private StringBuffer m_sb;
	
	public void init(){
		if (m_sb == null){
		    m_sb = new StringBuffer();
		}
	}
	
	public String m_parentName;
	private static final String CHANGE_LINES = "\n";
	
	public void startParent(String parentName){
		m_parentName = parentName;
		m_sb.append("<" + parentName + ">").append(CHANGE_LINES);
	}
	
	public void appendChild(String childName, String value){
		m_sb.append("<" + childName + ">").append("<" + value + ">").append("</" + childName + ">").append(CHANGE_LINES);
	}

	public String endParent(){
		m_sb.append("</" + m_parentName + ">").append(CHANGE_LINES);
		return m_sb.toString();
	}
}


